package processor

import (
	"bbq/common/protocol/remoteCommand"
	"bbq/common/protocol/request"
	"bbq/common/protocol/response"
	"bbq/namesrv/routeinfo"
	"encoding/json"
	"github.com/panjf2000/gnet"
)

type NamesrvProcessor struct {
	RouteInfoManager *routeinfo.RouteInfoManager
}

func (ns *NamesrvProcessor) ProcessRequest(conn gnet.Conn, req *remoteCommand.RemoteCommand) *remoteCommand.RemoteCommand {
	switch req.Header.Code {
	//注册broker
	case remoteCommand.REGISTER_BROKER:
		return ns.registerBroker(conn, req)

	//注销broker
	case remoteCommand.UNREGISTER_BROKER:
		return nil
	default:
		panic("unknown cmd")
	}
}

func (ts *NamesrvProcessor) registerBroker(conn gnet.Conn, req *remoteCommand.RemoteCommand) *remoteCommand.RemoteCommand {
	registerBrokerRequest := &request.RegisterBrokerRequest{}
	_ = json.Unmarshal(req.Body, registerBrokerRequest)
	//注册broker
	result := ts.RouteInfoManager.RegisterBroker(registerBrokerRequest.ClusterName, registerBrokerRequest.BrokerAddr,
		registerBrokerRequest.BrokerName, registerBrokerRequest.BrokerId, registerBrokerRequest.HaServerAddr,
		registerBrokerRequest.TopicConfigTable, registerBrokerRequest.DataVersion, conn)

	resp := response.RegisterBrokerResponse{
		HaServerAddr: result.HaServerAddr,
		MasterAddr:   result.MasterAddr,
	}

	body, _ := json.Marshal(resp)

	cmd := &remoteCommand.RemoteCommand{
		&remoteCommand.CmdHeader{
			Code:     remoteCommand.SUCCESS,
			Version:  int8(1),
			Opaque:   int64(2),
			ClientId: "3",
			Flag:     0,
		},
		body,
	}

	return cmd
}
